import Scene from './scene'
import BackGround from '../runtime/background'
import Sprite from '../base/sprite'
import util from '../base/util'
import rea from '../base/rea'
import rankPanel from '../base/switchPanel'

const screenWidth = window.innerWidth
const screenHeight = window.innerHeight

export default class AstrayMultiScene extends Scene {
  constructor(aParent, aOpenID) {
    super(aParent, aOpenID)
    this.bg = new BackGround.astraySingle()
    this.bindControl = this.control.bind(this)
    this.astray_level = new rankPanel("astray_level", {left: 0.2, height: 0.08, top: 0.63}, {height: 0.08, top: 0.63})
    this.player_count = new rankPanel("player_count", {left: 0.2, height: 0.08, top: 0.72}, {height: 0.08, top: 0.72})
    this.start_btn = new Sprite("images/astray/buttons.png", screenWidth * 0.5, screenHeight * 0.08, screenWidth * 0.2, screenHeight * 0.81, 2,
    {sx: 248, sy: 276, sw: 200, sh: 170, texts: [{value: "开始挑战", font: screenHeight * 0.04 + 'px Arial', pos: [screenWidth * 0.16, screenHeight * 0.056], color: "#ffffff"}]}, "multi_start")
    this.pswd_btn = new Sprite("images/astray/pswd.png", screenWidth * 0.1, screenHeight * 0.08, screenWidth * 0.7, screenHeight * 0.81, 2, null, "multi_pswd")
    this.return_btn = new Sprite("images/astray/buttons.png", screenWidth * 0.6, screenHeight * 0.08, screenWidth * 0.2, screenHeight * 0.9, 2,
    {sx: 470, sy: 276, sw: 200, sh: 170, texts: [{value: "返回", font: screenHeight * 0.04 + 'px Arial', pos: [screenWidth * 0.23, screenHeight * 0.05], color: "#ffffff"}]}, "multi_return")
    this.rank = new rankPanel("multi_rank", {left: 0.1, height: 0.52, top: 0.1}, {height: 0.1, top: 0.4})
    this.waiting_panel = new Sprite("images/astray/buttons.png", screenWidth * 0.6, screenHeight * 0.32, screenWidth * 0.2, screenHeight * 0.26, 3, {sx: 248, sy: 276, sw: 200, sh: 170, texts: [{value: "等待对手", font: screenHeight * 0.04 + 'px Arial', pos: [screenWidth * 0.16, screenHeight * 0.056], color: "#ffffff"}]}, "multi_waiting")
    this.cancel_wait = new Sprite("images/astray/buttons.png", screenWidth * 0.4, screenHeight * 0.08, screenWidth * 0.3, screenHeight * 0.48, 4, {sx: 470, sy: 276, sw: 200, sh: 170, texts: [{value: "取消", font: screenHeight * 0.04 + 'px Arial', pos: [screenWidth * 0.12, screenHeight * 0.056], color: "#ffffff"}]}, "multi_cancel")
    this.rank_updated = true
    this.waiting = false

    wx.onKeyboardConfirm(e => {
      if (this.parent.current_scene == "loading2")
        this.password = e.value
    })

    rea.pipelines().find("fromServer").nextF(aInput => {
      let inf2 = aInput.data()
      if (inf2.type == "playing")
        if (!this.waiting && this.parent.current_scene == "loading2" && this.lastScene == "start"){
          this.waiting = true
          this.remain = 0
          this.__prepareMatch(this.openid)
        }
    })
  }

  initEnter(){
    Scene.prototype.enter.apply(this, arguments)
    canvas.addEventListener('touchstart', this.bindControl)
  }
  async enter(aInfo){
    this.lastScene = aInfo.lastScene
    this.password = ""
    this.rank_updated = false
    this.rank.enterSwitch3D(1, 1, 1)
    this.initEnter()
    this.astray_level.enterSwitch3D(10, 5, 20)
    this.player_count.enterSwitch3D(2, 1, 8)
  }

  leave(){
    canvas.removeEventListener('touchstart', this.bindControl)
  }

  __clearWaiting(){
    this.waiting = false
    this.waiting_panel.clear(this.ctx)
    this.cancel_wait.clear(this.ctx)
  }

  __prepareMatch(player){
    if (this.cancel){
      this.__clearWaiting()
      this.cancel = false
      util.request({
        api: "astray/gameFinish",
        data: {openid: this.openid}
      })
    }else if (this.waiting){
      setTimeout(e=>{
        this.waiting_panel.visible = true
        this.cancel_wait.visible = true
        util.request({
          api: "astray/prepareGame",
          data: {openid: player,
                count: this.player_count.current_stage,
                level: this.astray_level.current_stage,
                password: this.password || ""}})
        .then(async res => {
          if (res.data.match_id){
            this.__clearWaiting()
            this.lastScene = null
            this.toNextScene("remote",  {mode: "multi", level: res.data.level, match_id: res.data.match_id})
          }else {
            this.remain = res.data.remain || "0"
            this.waiting_panel.customUpdate({sx: 248, sy: 276, sw: 200, sh: 170, texts: [{value: "等待" + this.remain + "个对手", font: screenHeight * 0.04 + 'px Arial', pos: [screenWidth * 0.12, screenHeight * 0.056], color: "#ffffff"}]})
            this.__prepareMatch(player)
          }
        })
      }, 1000)
    }
  }

  control(e){
    e.preventDefault()
    const x = e.touches[0].clientX
    const y = e.touches[0].clientY
    if (this.waiting){
      if (this.cancel_wait.pointIsIn(x, y)){
        this.cancel = true
      }
      return
    }
    if (this.start_btn.pointIsIn(x , y)){
      this.waiting = true
      this.remain = this.player_count.current_stage
      this.__prepareMatch(this.openid)
    }else if (this.return_btn.pointIsIn(x, y)){
      this.toNextScene("start")
    }else if (this.pswd_btn.pointIsIn(x, y)){
      wx.showKeyboard()
    }else{ 
      this.player_count.controlSwitch3D(x, y)
      this.astray_level.controlSwitch3D(x, y)
    }
  }

  update(){
    return Scene.prototype.update.apply(this, arguments)
    // this.bg.update(ctx)
  }
  async render(ctx){
    this.ctx = ctx
    Scene.prototype.render.apply(this, arguments)
    this.bg.render(ctx)
    this.start_btn.drawToCanvas(ctx)
    this.return_btn.drawToCanvas(ctx)
    this.pswd_btn.drawToCanvas(ctx)
    let txts = []
    if (!this.rank_updated){
      let res = await util.request({
        api: "astray/listusers",
        data: {}})
      let rec = res.data
      rec.sort((p, n) => {  //get best stage
        return p.level - n.level
      })
      if (rec.length){
        txts.push({value: "排名", font: screenHeight * 0.03 + 'px Arial', pos: [screenWidth * 0.08, screenHeight * 0.07], color: "#ffffff"})
        txts.push({value: "用户", font: screenHeight * 0.03 + 'px Arial', pos: [screenWidth * 0.34, screenHeight * 0.07], color: "#ffffff"})
        txts.push({value: "积分", font: screenHeight * 0.03 + 'px Arial', pos: [screenWidth * 0.62, screenHeight * 0.07], color: "#ffffff"})
        for (let i = 0; i < 10 && i < rec.length; ++i){
          let idx = i
          let clr = "#ffffff"
          let usr = rec[idx].openid.substr(0, 3) + "**" + rec[idx].openid.substr(rec[idx].openid.length - 3, 3)
          if (rec[idx].openid == this.openid){
            clr = "#ff0000"
            usr = "你的位置"
          }
          let ht = screenHeight * 0.07 + (i + 1) * screenHeight * 0.05
          txts.push({value: i + 1, font: screenHeight * 0.03 + 'px Arial', pos: [screenWidth * 0.1, ht], color: clr})
          txts.push({value: usr, font: screenHeight * 0.03 + 'px Arial', pos: [screenWidth * 0.28, ht], color: clr})
          txts.push({value: rec[idx].level, font: screenHeight * 0.03 + 'px Arial', pos: [screenWidth * 0.61, ht], color: clr})
        }
      }else{
        txts.push({value: "没有记录", font: screenHeight * 0.04 + 'px Arial', pos: [screenWidth * 0.28, screenHeight * 0.34], color: "#ffffff"})
      }
      this.rank_updated = true
    }
    await this.rank.renderSwitch3D(ctx, txts)
    await this.player_count.renderSwitch3D(ctx,  [{value: this.player_count.current_stage + "人", font: screenHeight * 0.04 + 'px Arial', pos: [screenWidth * 0.24, screenHeight * 0.055], color: "#ffffff"}])
    await this.astray_level.renderSwitch3D(ctx, [{value: this.astray_level.current_stage + "级", font: screenHeight * 0.04 + 'px Arial', pos: [screenWidth * 0.24, screenHeight * 0.055], color: "#ffffff"}])
    if (this.waiting){
      this.waiting_panel.drawToCanvas(ctx, true)
      this.cancel_wait.drawToCanvas(ctx)
    }
    ctx.update()
  }
}